<template>
    <jb-crud-page
        ref="pageRef"
        :edit-component="DeptEdit"
        edit-modal-width="1200px"
        @after-submit="loadTreeData()"
    >
        <template #title>
            <jb-icon icon="mingcute:department-fill" class="text-20px"></jb-icon>
            <span class="ml-8px">部门管理</span>
            <jb-btn
                :icon="Icons.EXPAND"
                text
                class="ml-24px"
                type="success"
                @click="tableRef?.setAllTreeExpand(true)"
            >
                展开
            </jb-btn>
            <n-divider vertical />
            <jb-btn
                :icon="Icons.SHRINK"
                text
                type="warning"
                @click="tableRef?.clearTreeExpand()"
            >
                收起
            </jb-btn>
        </template>
        <template #conditions>
            <n-input
                v-model:value="searchForm.keywords"
                clearable
                type="text"
                placeholder="请输入关键字进行过滤"
            />
        </template>
        <template #opt>
            <n-button-group>
                <jb-btn
                    :icon="Icons.ADD"
                    ghost
                    type="primary"
                    @click="pageRef?.showEditModal('添加部门')"
                    >新增</jb-btn
                >
                <jb-btn
                    :icon="Icons.REFRESH"
                    ghost
                    type="warning"
                    @click="loadTreeData()"
                >
                    刷新
                </jb-btn>
            </n-button-group>
        </template>
        <template #default>
            <jb-table
                ref="tableRef"
                :tree-config="{ childrenField: 'items', reserve: true }"
                :data="showData"
            >
                <jb-column
                    align="left"
                    header-align="center"
                    field="name"
                    title="部门名称"
                    tree-node
                    type="html"
                    min-width="200"
                    fixed="left"
                ></jb-column>
                <jb-column
                    field="fullName"
                    title="部门全称"
                    type="html"
                    min-width="240"
                ></jb-column>
                <jb-column title="部门类型" width="160">
                    <template #default="{ row }">
                        <span :class="`type type_${row.type}`">{{ row?.typeName }}</span>
                    </template>
                </jb-column>
                <jb-column
                    field="sn"
                    title="部门编号"
                    type="html"
                    width="100"
                ></jb-column>
                <jb-column
                    field="leader"
                    title="负责人"
                    type="html"
                    width="100"
                ></jb-column>
                <jb-column
                    field="phone"
                    title="联系电话"
                    type="html"
                    width="130"
                ></jb-column>
                <jb-column
                    field="remark"
                    title="备注"
                    type="html"
                    min-width="200"
                ></jb-column>
                <jb-column field="enable" title="是否启用" width="80" fixed="right">
                    <template #default="{ row }">
                        <jb-switch
                            v-model:value="row.enable"
                            confirm="确定切换此部门的状态？"
                            :url="`/api/admin/dept/toggleEnable/${row.id}`"
                            @change="loadTreeData()"
                        ></jb-switch>
                    </template>
                </jb-column>
                <jb-column title="操作" width="140" fixed="right" align="center">
                    <template #default="{ row }">
                        <jb-btn
                            tip-text="添加子部门"
                            :icon="Icons.ADD"
                            secondary
                            circle
                            type="primary"
                            @click="
                                pageRef?.showEditModal('添加子部门', {
                                    pid: row.id
                                })
                            "
                        ></jb-btn>
                        <jb-btn
                            tip-text="编辑"
                            :icon="Icons.EDIT"
                            secondary
                            class="mx-8px"
                            type="warning"
                            circle
                            @click="
                                pageRef?.showEditModal('修改部门', {
                                    id: row.id,
                                    pid: row.pid
                                })
                            "
                        ></jb-btn>
                        <jb-btn
                            tip-text="删除"
                            confirm-text="确认删除该部门吗？"
                            :url="`/api/admin/dept/delete/${row.id}`"
                            :icon="Icons.DELETE"
                            secondary
                            type="error"
                            circle
                            @success="loadTreeData()"
                        ></jb-btn>
                    </template>
                </jb-column>
            </jb-table>
        </template>
    </jb-crud-page>
</template>
<script setup lang="ts">
import { nextTick, onMounted, reactive, ref, watch } from 'vue'
import XEUtils from 'xe-utils'
import { JBoltApi } from '@/utils/request'
import type { ResData } from '@/typings/request'
import JbCrudPage from '@/components/_builtin/jb-crud-page/index.vue'
import { Icons } from '@/constants/icons'
import { Model } from '@/typings/api'
import DeptEdit from './components/dept-edit/index.vue'
import type { VxeTableInstance } from 'vxe-table'

const pageRef = ref<InstanceType<typeof JbCrudPage> | null>(null)
const tableRef = ref<VxeTableInstance<Model>>()
/* 查询相关 start */
const searchForm = reactive({
    keywords: ''
})
watch(
    () => searchForm.keywords,
    XEUtils.debounce(() => {
        search()
    }, 500)
)

function search() {
    const filterVal = XEUtils.toValueString(searchForm.keywords).trim().toLowerCase()
    if (filterVal) {
        const filterRE = new RegExp(filterVal, 'gi')
        const options = { children: 'items' }
        const searchProps = ['name', 'sn', 'fullName', 'remark', 'phone', 'leader']
        const rest = XEUtils.searchTree(
            tableData.value,
            (item) =>
                searchProps.some(
                    (key) => String(item[key]).toLowerCase().indexOf(filterVal) > -1
                ),
            options
        )
        XEUtils.eachTree(
            rest,
            (item) => {
                searchProps.forEach((key) => {
                    if (!item[key]) return
                    item[key] = String(item[key]).replace(
                        filterRE,
                        (match) => `<span class="keyword-lighten">${match}</span>`
                    )
                })
            },
            options
        )
        showData.value = rest
        // 搜索之后默认展开所有子节点
        nextTick(() => {
            const $table = tableRef.value
            if ($table) {
                $table.setAllTreeExpand(true)
            }
        })
    } else {
        showData.value = tableData.value
    }
}

/* 查询相关 end */

/* 主表相关 start */
const tableData = ref<Model[]>([])
const showData = ref<Model[]>([])
const loading = ref(false)
async function loadTreeData() {
    if (loading.value) return
    loading.value = true
    const res = await JBoltApi.tryGet<ResData<Model[]>>(`/api/admin/dept/datas?pid=0`)
    loading.value = false
    tableData.value = res.data!
    search()
}

onMounted(() => {
    loadTreeData()
})
/* 主表相关 end */
</script>

<style scoped lang="scss">
.type {
    font-size: 12px;
    color: white;
    padding: 2px 4px;
    border-radius: 4px;
}
$bg-colors: (
    type_1: #0000ff,
    type_2: #0080ff,
    type_3: #ff8000,
    type_4: #d79b57,
    type_5: #8a1896,
    type_6: #b51ac3,
    type_7: #329115,
    type_8: #3fbe16,
    type_9: #1b9999,
    type_10: #14bcbc
);

@each $class, $color in $bg-colors {
    .#{$class} {
        background-color: $color;
    }
}
</style>
